#include "ftpclientpanel.h"
#include "ui_ftpclientpanel.h"
#include <QtNetwork>
#include <QDebug>
#include <QDirModel>
#include <QListWidgetItem>
#include <QTextCodec>
#include <QFileInfo>
#include <QSettings>


FtpClientPanel::FtpClientPanel(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FtpClientPanel)
{
    ui->setupUi(this);
    ui->groupBox_CP->hide();
    ui->groupBox_SR->hide();

    disconnect = false;
    ui->localTab->removeTab(1);
    ui->remoteTab->removeTab(1);
    ui->logTab->removeTab(1);
    ui->downloadProgress->setMaximum(100);
    ui->downloadProgress->setValue(0);
    ui->remoteFiles->setEnabled(false);
    ui->downloadButton->setEnabled(false);

    ui->btn_UP->setIcon(QPixmap(":/Images/Images/add_bottom_blue.png"));
    ui->btn_DN->setIcon(QPixmap(":/Images/Images/add_top_blue.png"));

    ui->downloadButton->setIcon(QPixmap(":/Images/Images/downloadPressed.png"));

    fileModel = new QFileSystemModel;
   // fileModel->setRootPath(QDir::currentPath());
    fileModel->setRootPath("/home/python/other");
    ui->localFiles->setModel(fileModel);
    ui->uploadButton->setEnabled(false);
    ui->localFiles->expandAll();
    ui->remoteFiles->setContextMenuPolicy(Qt::CustomContextMenu);
    totalBytes      = 0;
    bytesDownloaded = 0;
    bytesUploaded   = 0;
    LoadFtpConfig();
}

FtpClientPanel::~FtpClientPanel()
{
    delete ui;
    delete ftp;
    delete fileModel;
}


QString FtpClientPanel:: _FromSpecialEncoding(const QString &InputStr)
{
   #ifdef Q_OS_WIN
      return QString::fromLocal8Bit(InputStr.toLatin1());
  #else
    QTextCodec *codec = QTextCodec::codecForName("GBK");
    if (codec)
    {
       return codec->toUnicode(InputStr.toLatin1());
    }
    else
    {
       return QString("");
    }
 #endif
}

QString FtpClientPanel::_ToSpecialEncoding(const QString &InputStr) {
    #ifdef Q_OS_WIN
        return QString::fromLatin1(InputStr.toLocal8Bit());
    #else
        QTextCodec *codec= QTextCodec::codecForName("GBK");
        if (codec) {
            return QString::fromLatin1(codec->fromUnicode(InputStr));
        } else {
            return QString("");
        }
    #endif
}


void FtpClientPanel::SaveFtpConfig()
{
    QString  dirPath =  QCoreApplication::applicationDirPath() +"/config/ftp.ini";
    if (!dirPath.isEmpty())
    {
        QFileInfo fileInfo(dirPath);
        if (fileInfo.exists())
        {
            QFile file(dirPath);
            file.remove();
        }
    }

    QSettings *settings = new QSettings(dirPath, QSettings::IniFormat);
     settings->beginGroup("Ftp");
     settings->setValue("ServerIPAddress",ui->address->text());
     settings->setValue("Port",ui->port->text());
     settings->setValue("UserName",ui->username->text());
     settings->setValue("Password",ui->password->text());
     settings->endGroup();
}

void FtpClientPanel::LoadFtpConfig()
{
    QString  dirPath =  QCoreApplication::applicationDirPath() +"/config/ftp.ini";
    QSettings *settings = new QSettings(dirPath, QSettings::IniFormat);
     settings->beginGroup("Ftp");
     ui->address->setText(settings->value("ServerIPAddress","127.0.0.1").toString());
     QString str = settings->value("Port","6000").toString();
     ui->port->setText(str);
     ui->username->setText(settings->value("UserName","admin").toString());
     ui->password->setText(settings->value("Password","123456").toString());
     settings->endGroup();

}


void FtpClientPanel::getRemoteFiles(QString path){

    ftp->list(path);
}

void FtpClientPanel::connected(){
    ui->connectButton->setText("Disconnect!");
    disconnect = true;
    getRemoteFiles();
    ui->remoteFiles->setEnabled(true);
}


void FtpClientPanel::disconnected(){
    ui->remoteFiles->clear();
    ui->remoteFiles->setEnabled(false);
    ui->downloadButton->setEnabled(false);
    ui->uploadButton->setEnabled(false);
    ui->downloadProgress->setValue(0);
    ui->logTextEdit->appendPlainText("You have been disconnected!");
    ui->connectButton->setText("Connect!");
    disconnect = false;


}

void FtpClientPanel::response(QString response){
    ui->logTextEdit->appendPlainText(response);
}

void FtpClientPanel::message(QString message){
    ui->logTextEdit->appendPlainText(message);
}

void FtpClientPanel::on_remoteFiles_itemDoubleClicked(QTreeWidgetItem *item, int column){
    QString path = item->text(0);
    getRemoteFiles(path);
}


void FtpClientPanel::on_localFiles_clicked(const QModelIndex &index){
    ui->uploadButton->setEnabled((fileModel->fileInfo(index).isFile()) ? true : false);
}

void FtpClientPanel::on_remoteFiles_itemClicked(QTreeWidgetItem *item, int column){
    ui->downloadButton->setEnabled((item->text(2) == "File") ? true : false);
}


void FtpClientPanel::addToServerList(const QUrlInfo &urlInfo)
{
    //qDebug() << "addToServerList " <<_FromSpecialEncoding(urlInfo.name());
    QListWidgetItem* item = new QListWidgetItem(urlInfo.name());

    QPixmap pixmap(urlInfo.isDir() ? ":/images/dir.png" : ":/images/file.png");
    item->setIcon(QIcon(pixmap));

    // Search the item in the list
   // QList<QListWidgetItem *> listItems = ui->listWidget_server->findItems(urlInfo.name(), Qt::MatchExactly);

    // Not found in the list, add to list
   // if(0 == listItems.size())
   // {
      //  ui->listWidget_server->addItem(item);
       // isServerDirectory[_FromSpecialEncoding(urlInfo.name())] = urlInfo.isDir();
  //  }
}


void FtpClientPanel::populateList(QVector<FileInfo> fileInfo){

   // QUrlInfo
   // qDebug()<<" MainWindow::populateList　fileInfo size："<<fileInfo.size();
    ui->remoteFiles->clear();
    QVector<FileInfo> files = fileInfo;
    int i =1,len = fileInfo.size();
    foreach(FileInfo file, files){
        QTreeWidgetItem *item = new QTreeWidgetItem;
      //  qDebug()<<i<<". \n\r"<<file.getName();
        item->setText(0, file.getName());
        item->setText(1, (file.isDir()) ? "" : QString::number(file.getSize()));
        item->setText(2, (file.isDir()) ? "File Folder" : "File");
        item->setText(3, file.getLastModified().toString("MM-dd-yy  hh:mm"));

        QPixmap pixmap(file.isDir() ? ":/icons/icons/folder.png" : ":/icons/icons/file.png");
        item->setIcon(0, pixmap);
        ui->remoteFiles->addTopLevelItem(item);
        i++;
        if(i>=len)break;
    }
}

void FtpClientPanel::populateDownloadBar(qint64 bytes){
    bytesDownloaded += bytes;

   // qDebug()<<"bytes:"<<bytes<<" bytesDownloaded:"<<bytesDownloaded<<"  totalBytes: "<<totalBytes;

    if(totalBytes>0){
        double db = (double)((double)bytesDownloaded /(double)totalBytes);
        int progress = int(db *(double)100);
        // qDebug()<<"populateDownloadBar progress:"<<progress;
        if(progress>=100)progress=100;
        if(progress<0)progress=0;
        ui->downloadProgress->setValue(progress);
    }

}

void FtpClientPanel::populateUploadBar(qint64 bytes){
    bytesDownloaded += bytes;

    if(totalBytes>0){
        double db = (double)((double)bytesDownloaded /(double)totalBytes);
        int progress = int(db *(double)100);
        // qDebug()<<"populateDownloadBar progress:"<<progress;
        if(progress>=100)progress=100;
        if(progress<0)progress=0;

        ui->downloadProgress->setValue(progress);
    }
}


void FtpClientPanel::on_btn_UP_clicked()
{
    if(ui->groupBox_CP->isHidden())
    {
        ui->groupBox_CP->show();
       ui->btn_UP->setIcon(QPixmap(":/Images/Images/add_top_blue.png"));
    }
    else
    {
        ui->groupBox_CP->hide();
        ui->btn_UP->setIcon(QPixmap(":/Images/Images/add_bottom_blue.png"));
    }
}

void FtpClientPanel::on_btn_DN_clicked()
{
    if(ui->groupBox_SR->isHidden())
    {
        ui->groupBox_SR->show();
        ui->btn_DN->setIcon(QPixmap(":/Images/Images/add_bottom_blue.png"));
    }
    else
    {
        ui->groupBox_SR->hide();
        ui->btn_DN->setIcon(QPixmap(":/Images/Images/add_top_blue.png"));
    }
}

void FtpClientPanel::on_connectButton_clicked()
{
    if(!disconnect){
        ftp = new Ftp(); // Delete this

        connect(ftp, SIGNAL(connectedToServer()), this, SLOT(connected()));
        connect(ftp, SIGNAL(disconnectedFromServer()), this, SLOT(disconnected()));
        connect(ftp, SIGNAL(response(QString)), this, SLOT(response(QString)));
        connect(ftp, SIGNAL(message(QString)), this, SLOT(message(QString)));
        connect(ftp, SIGNAL(listDone(QVector<FileInfo>)), this, SLOT(populateList(QVector<FileInfo>)));
        connect(ftp, SIGNAL(toDownloadBar(qint64)), this, SLOT(populateDownloadBar(qint64)));
        connect(ftp, SIGNAL(toUploadBar(qint64)), this, SLOT(populateUploadBar(qint64)));

        QString address = ui->address->text();
        quint16 port = ui->port->text().toInt();

        QString username = (ui->username->text().isEmpty()) ? "admin" : ui->username->text();
        QString password = (ui->password->text().isNull()) ? "123456" : ui->password->text();

        ftp->connectToHost(address, port, username, password);


    } else {
        ftp->disconnectFromHost();
        ui->connectButton->setText("Connect!");
        disconnect = false;
         SaveFtpConfig();

    }
}

void FtpClientPanel::on_downloadButton_clicked()
{
    ui->downloadButton->setEnabled(false);
    ui->downloadProgress->setValue(0);
    bytesDownloaded = 0;
    totalBytes      = 0;
    QString fileName = ui->remoteFiles->currentItem()->text(0);
    QModelIndex index = ui->localFiles->currentIndex();
    QString savePath = fileModel->filePath(index) + "/" + fileName;
    QString sss =ui->remoteFiles->currentItem()->text(1);
    if(!sss.isEmpty())
    {
        totalBytes = sss.toLong();
    }

   ftp->get(fileName, savePath);

    qDebug()<<"ftp->get:"<<fileName<<" savePath:"<<savePath<<" totalBytes:"<<totalBytes;

    ui->downloadButton->setEnabled(true);
}

void FtpClientPanel::on_uploadButton_clicked()
{
    ui->downloadProgress->setMaximum(100);
    ui->downloadProgress->setValue(0);
    bytesDownloaded = 0;
    totalBytes      = 0;
    QModelIndex index = ui->localFiles->currentIndex();
   // ui->uploadProgress->setMaximum(fileModel->size(index));
     ui->downloadProgress->setMaximum(fileModel->size(index));
    QString filePath = fileModel->filePath(index);
    QString fileName = '"' + fileModel->fileName(index) + '"';
    ftp->put(filePath, fileName);
}

void FtpClientPanel::on_btn_clear_clicked()
{
     ui->logTextEdit->clear();
}
